package com.zzs.team.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志（切面实现）
 */
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpServletRequest request;
    /**
     * 定义切入点表达式
     */
    @Pointcut("execution(* com.zzs.team.Controller.*.*(..))")
    public  void log(){

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        logger.info("--------before----------");
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        /*获取访问的类路径名 和 方法名*/
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("Request:{}",requestLog);
    }
    @After("log()")
    public void doAfter(){
        logger.info("----------after---------");
    }

    /***
     *
     * @param result:将切面返回的结果传给Object对象的result
     */
    @AfterReturning(pointcut = "log()",returning = "result")
    public void doAfterReturn(Object result){
        logger.info("Result:{}",result);
    }


    private class RequestLog{
        private String url;//访问的url
        private String ip;//访问的ip
        private String classMethod;//访问的方法
        private Object[] args;//访问的参数

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
